#! usr/bin/python3
# coding=utf-8
# @Time: 2025/9/20
# @Author: GaoSheng
import logging

import requests

from base.utils import join_urls, merge_dicts


class HttpClient:
    def __init__(self, base_url, session=None, **kwargs):
        self.base_url = base_url
        if session and not isinstance(session, requests.Session):
            raise TypeError('need the instance of requests.Session class')
        self.session = session
        self.logger = logging.getLogger(__name__)
        self.req_kwargs = dict(timeout=90)

    def _call_api(self, endpoint, method="post", req_kwargs=None):
        """http调用函数

        :param endpoint: 接口地址,用self.base_url拼接成完整的请求地址
        :param method: http请求方式
        :param req_kwargs: 透传给requests.request的请求参数（不包含url, method）
        :return:
        """
        url = join_urls(self.base_url, endpoint)
        kwargs = self.req_kwargs.copy()
        merge_dicts(kwargs, req_kwargs)

        self.logger.info("start request", extra=dict(method=method, parameters=kwargs, url=url))

        if not self.session:
            self.session = requests.session()
        response = self.session.request(method, url, **kwargs)

        self.logger.info("got response",
                         extra=dict(response=response.text, url=response.url, status_code=response.status_code))

        response.raise_for_status()  # requests 自带对status code检查的方法,对>=400的status code 抛出异常

        try:
            resp_to_json = response.json()
        except ValueError:
            self.logger.error('convert response to json fail')
            raise

        return resp_to_json
